package org.apache.ocean.util;

import java.lang.ref.*;
import java.util.*;

/**
 *
 * @author jasonr
 */
public class WeakRefManager<T> {
  public ReferenceQueue<T> referenceQueue = new ReferenceQueue<T>();
  public List<WeakReference<T>> references = new ArrayList<WeakReference<T>>();
  
  public WeakRefManager() {
  }
  
  public static class Ref<T> {
    WeakRefManager weakRefManager;
    Reference<? extends T> reference;
    T object;
    
    public Ref(Reference<? extends T> reference, T object, WeakRefManager weakRefManager) {
      this.reference = reference;
      this.object = object;
      this.weakRefManager = weakRefManager;
    }
    
    public T get() {
      return object;
    }
    
    public void remove() {
      reference.clear();
      weakRefManager.references.remove(reference);
    }
  }
  
  public Ref<T> poll(long duration) throws Exception {
    Reference<? extends T> reference = referenceQueue.remove(duration);
    if (reference != null) {
      T object = reference.get();
      return new Ref(reference, object, this);
    }
    return null;
  }
  
  public void add(T object) {
    references.add(new WeakReference(object, referenceQueue));
  }
}
